package com.woniuxy.dudugua.util.qnyutil;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Component;

import java.io.InputStream;
//---------lzm
//---------2020.5.22
//··········七牛云文件上传接口
//···········请在文件名前加入  前缀!!!!!!!!!!!!!!!!!!!
//···········如是ai测颜值功能 aiface/image.jpg
//···········商品介绍图product/image.jpg  商品详情图  product/info/image.jpg
//           商品介绍视频product/video/video.avi
//           头像 headPortrait/iamge.jpg
//               ↑  ↑
//               ↑  ↑
//               ↑  ↑
//               ↑  ↑
//           调用前请读文档
@Component
public class QiniuUtil {

    //设置识别用的各种KEY
    private static final String ACCESS_KEY = "6v3HlKnFoLVWldaW5_EyguQLHUHHBI2nKiXriuK4";
    private static final String SECRET_KEY = "jZMKRELlo5dLx9-zfa4VYI9CcYkIz2eIHJMhBscK";
    private static final String BUCKET = "dudguaer";

    public void upload(String fileKey, InputStream fileStream) {
        //提供配置信息
        Configuration cfg = new Configuration(Zone.autoZone());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String upToken = auth.uploadToken(BUCKET);

        Response response = null;
        try {
            //上传
            response = uploadManager.put(fileStream, fileKey, upToken,null,null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException e) {
            throw new RuntimeException("上传文件出错",e);
        }
    }

    private  final String CDN_DOMAIN = "http://www.luzmzm.cn/";

    //生成用于全局访问的网络地址，实际应用时可以直接存入数据库
    public  String fullPath(String fileKey){
        return CDN_DOMAIN+fileKey;
    }

}
